local ServerOHOH = _G.ServerOHOH;
local M = ServerOHOH.class.new(script, ServerOHOH.files.Server_PlayerComponent(),script.Parent.Name);
local function_list = ServerOHOH.function_list;
local FriendBoost=ServerOHOH.config.Game.FriendBoost
local ConnectClass=_G.CommonOHOH.load.Connect();
local game_cfg= ServerOHOH.config.Game
local Tool=require(script.Parent.tool)
local runService =game:GetService("RunService")
local SceneFolder=workspace:WaitForChild("Scene")

local drag =1
local force = 120
local yAxis  = 0

---配置的walkspeed
local gWalkSpeed=game_cfg.WalkSpeed

function M.new(self,...)
	return M(self,...);
end;

function M.ctor(self, parent)
	M.super.ctor(self, parent);
    self.userId=self.parent:GetUserId()
    self.player = self.parent
   
    -- self.cdTime = 5 --车辆销毁时间
    self.DataBase=self.parent:GetComponent(ServerOHOH.load.Server_PlayerDataComponent())

    self.needTime = game_cfg.CarCollectionTime--车辆销毁时间

    self.HomeCarList = {}
    self.TouchList = {}
    self.DataCtrl =  _G.server:GetComponent(_G.ServerOHOH.load.Server_PVPDataStoreCtrl())
    

    self.playerAddConnect=game.Players.PlayerAdded:Connect(function(player)
       print("player added",player.UserId)
   end)

    self.playerRemoveConnect= game.Players.PlayerRemoving:Connect(function(player)
        print("————————————————玩家离开————————————————————")
        -- if self.userId == player.UserId then
        --     if  self.DriveCarConnection then
        --         self.DriveCarConnection:Disconnect()
        --         self.DriveCarConnection =nil
        --     end
        -- end
        self:DestroyCar(player.UserId)
        self:DestroyTouch(player.UserId)
    end)

    self.CarSkinData = self:GetCarSkinData()
    self:CreateHomeCar(self.CarSkinData)

    self:ClearParkingInfo()
end;

--隐藏未使用车位的UI信息
function M.ClearParkingInfo(self)
    
    for _,model in pairs(SceneFolder:GetChildren()) do
        for i = 1, 12 do
            local path=string.format("Parking.%s.Spawn",i) --碰撞体路径
            local touch=ServerOHOH:GetPath_Loop(path,model)
            local isUsing = touch:GetAttribute("isUsing")
            if not isUsing then
                self:Hide(ServerOHOH:GetPath_Loop("Attachment.BillboardGui", touch))
            end
        end
    end
end;

-- 深拷贝函数
function M.DeepCopy(self,original)
    if type(original) ~= "table" then
        return original -- 非表类型直接返回值
    end
    local copy = {}
    for key, value in pairs(original) do
        copy[key] = self:DeepCopy(value) -- 递归拷贝
    end
    return copy -- 返回深拷贝
end

-- 修改 GetCarSkinData
function M.GetCarSkinData(self)
    local data = self.DataBase:GetData("car").skin.__real
    return self:DeepCopy(data) -- 返回深拷贝
end

--自动化测试开车（按照点位MoveTo）（未使用）
function M.CustomSelfDrive(self)
    local wayFolder = workspace:FindFirstChild("WayPoints") -- 替换为你的文件夹路径
    if not wayFolder then
        warn("Folder 'Way' not found in workspace!")
        return
    end
    
    local parts = {} -- 用来存储按编号排序的 Part
    
    -- 遍历文件夹中的所有子对象
    for _, child in pairs(wayFolder:GetChildren()) do
        if child:IsA("BasePart") and tonumber(child.Name) then
            table.insert(parts, child)
        end
    end
    
    -- 按名称（编号）排序
    table.sort(parts, function(a, b)
        return tonumber(a.Name) < tonumber(b.Name)
    end)
    
    -- 遍历排序后的 Part，获取它们的位置
    for _, part in ipairs(parts) do
        print("Part Name:", part.Name, "Position:", part.Position)
    end
    



    local CarModel = self.Car:GetModel()


    for _, part in ipairs(parts) do
        local  success = false
        CarModel.Humanoid:MoveTo(part.Position)
        
        while not success do
            print("true")
             local distance = (CarModel.HumanoidRootPart.Position - part.Position).Magnitude
            if distance < 20 then
                success = true
            end
            task.wait(0.1)
        end
      
    end

end





function M.CreateHomeCar(self,skinData)
    print("_______CreateHomeCar————————")
    local myCarData = {Tool.GetAllCarIdBySkinData(skinData)}

    if self.Car then
        return 
    else  
        if  not self.touch  then
            for _,model in pairs(SceneFolder:GetChildren()) do
                for i = 1, 12 do
                    local path=string.format("Parking.%s.Spawn",i) --碰撞体路径
                    local touch=ServerOHOH:GetPath_Loop(path,model)
                    local isUsing = touch:GetAttribute("isUsing")
                    if not isUsing then
                        print("_______占用点位————————")
                        self.touch = touch
                        self.touch:SetAttribute("isUsing", true)
                        self.TouchList[self.userId] = self.touch   
                        self:CreateInfo(self.touch) 
                        break
                    end
                end
            end
        end
        
    
        print("不存在我的Car，创建",myCarData)
        self.Car =_G.CommonOHOH.load.HomeCar().new(self.parent,myCarData[1],myCarData[2],myCarData[3],myCarData[4],myCarData[5])
        
        self.Car:SetCFrame(self.touch.CFrame)
        self.Car:AnchoredSwitch(false)

        self.Car:SetEmitterStatus(false)
        self.Car:SetDrillingSpeed(0)

        self.Car:SetSeatDisabled()
        self.Car:SetPromptStatus(true)
        self.Car:SetCanCollide(true)

        self.Car:SetParent(Workspace)
    
    --离开事件
        self.Car.LeaveCarEvent:Connect(function()
            -- --倒计时删除车辆
            self:StartUpdateTime()
            self.Car:SetEmitterStatus(false)
            self.Car:SetDrillingSpeed(0)
            print("leave event")
            self.Car:CustomLeaveCar()
        end)

    --坐下事件
        self.Car.SitCarEvent:Connect(function()
            print("————————————————坐车 player 服务器————————————————————" )
            if self.update_connect then
                -- print("暂停倒计时")
                self.update_connect:Disconnect();
                self.update_connect=nil;
            end

            -- self:Drive()--使用动力学（龙）
            self.Car:CustomDrive()--使用humanoid
            -- self:CustomSelfDrive() --使用路径
            
            --关闭、重置倒计时
            -- print("重置")
            self.needTime = game_cfg.CarCollectionTime--车辆销毁时间
        end)
        self.HomeCarList[self.userId] =  self.Car
    end
   
end;

--更新车辆、参数：bool （是否无论相同，强制重置）
function M.Refresh(self,forceRefresh)
    
    --更新皮肤
    if  self.update_connect then
        self.update_connect:Disconnect();
        self.update_connect=nil;
    end
    -- if  self.DriveCarConnection then
    --     self.DriveCarConnection:Disconnect()
    --     self.DriveCarConnection =nil
    -- end

    local refresh = self:GetCarSkinData()

    local isSame =Tool.IsSkinDataSame(self.CarSkinData,refresh)
    print("HomeCar更新车辆",self.CarSkinData,refresh)
    if not isSame then
        print("需要更新")
        self.CarSkinData =refresh
    else
        print("不需要更新")
        if not forceRefresh then---皮肤数据没有改变，且不需要更新
            return 
        end
    end
    if self.Car:GetCarUsing() then
        --更新车辆时如果在使用，会强制离开车辆
        self.Car:CustomLeaveCar()
    end
    --更新位置
    self:DestroyCar(self.userId)
    self.Car=nil
    self:AddProcess(function()
        self:CreateHomeCar(self.CarSkinData)
    end)
    return true
end;


--隐藏 UI
function M.Hide(self,uiobj)
    uiobj.Enabled=false
end
--显示 UI
function M.Show(self,uiobj)
    uiobj.Enabled=true
end

--创建车位UI信息
function M.CreateInfo(self,touch)
    self.ui=ServerOHOH:GetPath_Loop("Attachment.BillboardGui", self.touch)
    self:Hide(self.ui)
    self.Head=ServerOHOH:GetPath_Loop("Ctrl.Head", self.ui).Value
    self.Name=ServerOHOH:GetPath_Loop("Ctrl.Name", self.ui).Value
end;

--填充UI信息
function M.InfoShow(self,head,name)
    
    print("self.Head",self.Head)
    print(" self.Name", self.Name)
    self.Head.Image = head
    self.Name.Text = name
    self:Show(self.ui)
end;


--倒计时
function M.Update(self)
	if(self.needTime<=0) and self.update_connect then
		--结束倒计时
		self.update_connect:Disconnect();
		self.update_connect=nil;
	end
   
	self.needTime=self.needTime-1;
    print("倒计时....",self.needTime)
	if(self.needTime==0)then
		--结束倒计时
        print("倒计时结束")
        self:Refresh(true)
	end
end

function M.StartUpdateTime(self)
    print("开始倒计时")
	if self.update_connect then
		return 
	end
	self.update_connect=self:AddStepUpdate(self.Update,1)
end
function M.dtor(self)

	M.super.dtor(self);
end;

--销毁点位
function M.DestroyCar(self,userId)
    
    if self.HomeCarList[userId] then
        print("————————销毁车辆——————————")
        self.HomeCarList[userId]:dtor()
    end
end;
--销毁点位
function M.DestroyTouch(self,userId)
    if self.TouchList[userId] then
        print("————————释放点位——————————")
        self:Hide(self.ui)
        self.TouchList[userId]:SetAttribute("isUsing", false)
    end
end;
--更新车辆皮肤
M:RegistFunction(function_list.refresh_car,M.Refresh)

--显示车位信息
M:RegistFunction(function_list.info_show,M.InfoShow)
return M



-- -- 未使用
-- function M.Drive(self)
--     print("_________Drive________")
--     self.Humanoid = self.player.character.main_inst.Humanoid
--     self.PrimaryPart = self.player.character.main_inst.PrimaryPart
--     self.RootPart = self.player.character.main_inst.HumanoidRootPart

--     self.VectorForce = self.Car:GetEngine():GetForce()
--     self.AlignOrientation = self.Car:GetEngine():GetAlign()

--     self.VectorForce.Attachment0 = self.PrimaryPart.RootRigAttachment
--     self.AlignOrientation.Attachment0 = self.PrimaryPart.RootRigAttachment
    
--     -- local  gravityVector = Vector3.new(0,0.8*game.Workspace.Gravity,0)
    


--     if not  self.DriveConnection then

--         self.VectorForce.Enabled = true
--         self.AlignOrientation.CFrame  = self.PrimaryPart.CFrame
--         self.AlignOrientation.Enabled = true

--         self.Humanoid:ChangeState(Enum.HumanoidStateType.Physics)

--         self.DriveConnection =runService.Heartbeat:Connect(function(deltaTime)
--             -- self.VectorForce.Force = gravityVector* self.PrimaryPart.AssemblyMass
--             self.VectorForce.Force = Vector3.zero
-- 			local moveVector = self.Humanoid.MoveDirection

--             local lookAtCFrame = CFrame.lookAt(self.RootPart.Position, workspace.CurrentCamera.CFrame.Position)
-- 			local moveVector = -lookAtCFrame.LookVector
-- 			local moveVector = Vector3.new(self.Humanoid.MoveDirection.X,yAxis,self.Humanoid.MoveDirection.Z)
            
--             local humanVelocity = self.RootPart.AssemblyLinearVelocity.Magnitude
--             self.Car:SetDrillingSpeed(humanVelocity)
--             if moveVector.Magnitude>0 then
--                 self.Car:SetEmitterStatus(true)
                
--                 moveVector = moveVector.Unit
                
--                 self.VectorForce.Force =self.VectorForce.Force+ moveVector* force * self.PrimaryPart.AssemblyMass
--                 self.AlignOrientation.CFrame = CFrame.lookAt(Vector3.zero,moveVector)

--             else
--                 --关闭旋转
--                 self.Car:SetEmitterStatus(false)
                
--                 --关闭特效
--             end



--             if self.PrimaryPart.AssemblyLinearVelocity.Magnitude >0 then
                
--                 local dragVector =-self.PrimaryPart.AssemblyLinearVelocity.Unit
--                 local v2 = self.PrimaryPart.AssemblyLinearVelocity.Magnitude ^1.2
--                 self.VectorForce.Force = self.VectorForce.Force + dragVector * drag * self.PrimaryPart.AssemblyMass * v2
--             end
--         end)
            
--     end
-- end;



--开车（使用车的Humanoid控制） 使用中
-- function M.CustomDrive(self)
--     local CarModel =self.Car:GetModel()
--     self.CarHumanoid= Instance.new("Humanoid",CarModel)
--     CarModel.HumanoidRootPart.Anchored=true
--     CarModel.Humanoid.WalkSpeed=0
--     CarModel.HumanoidRootPart.Anchored=false
--     local humanoid=self.player.character.main_inst.Humanoid
    
--     local seatlist= self.Car:GetBody():GetSeatList()
--     for _,s in pairs(seatlist)  do
--         if  not s:GetAttribute("isUsing") then
--             -- self.player.character.main_inst.HumanoidRootPart:PivotTo( s:GetPivot())
--             task.wait(0.2)
--             s.Disabled = false
--             s:SetAttribute("isUsing",true)
--             s:Sit(humanoid)
--            print("sit",s.Occupant)
--             break

--         end
--     end
   
-- 	humanoid.WalkSpeed=0
-- 	humanoid.DisplayDistanceType=Enum.HumanoidDisplayDistanceType.None
    

-- 	local Character=self.player.character.main_inst
-- 	self.sysCharacter=Character
-- 	-- local cf=CarModel:GetPrimaryPartCFrame()
-- 	self.player.main_inst.Character=CarModel
-- 	Character.Parent=CarModel
	
-- 	task.wait(0.1)

-- 	CarModel.Humanoid.WalkSpeed =gWalkSpeed
-- 	CarModel.Humanoid.AutoJumpEnabled = false;
-- 	CarModel.Humanoid.UseJumpPower = true;
-- 	CarModel.Humanoid.JumpPower=0

--     self.Car:SetCanCollide(true)

--     humanoid:ChangeState(Enum.HumanoidStateType.Seated) 

--     if not  self.DriveConnection then
--         self.DriveConnection =runService.Heartbeat:Connect(function(deltaTime)

--             local humanVelocity = CarModel.HumanoidRootPart.AssemblyLinearVelocity.Magnitude
--             self.Car:SetDrillingSpeed(humanVelocity)
--             -- print("humanVelocity",humanVelocity)
--             if humanVelocity>0.5 then
--                 self.Car:SetEmitterStatus(true)
--             else
--                 --关闭旋转
--                 self.Car:SetEmitterStatus(false)
    
--                 --关闭特效
--             end
--         end)
--     end

--     -- self:CustomSelfDrive()
-- end

--离开车(自定义 Humanoid切换的方式)
-- function M.CustomLeaveCar(self)
--     if  self.DriveConnection then
--         self.DriveConnection:Disconnect()
--         self.DriveConnection =nil
--     end
--     local CarModel =self.Car:GetModel()
--     local humanoid= self.sysCharacter.Humanoid
    
-- 	humanoid.WalkSpeed=0
-- 	humanoid.DisplayDistanceType=Enum.HumanoidDisplayDistanceType.Viewer
--     -- CarModel.HumanoidRootPart.Anchored=true

-- 	self.CarHumanoid.WalkSpeed=0
--     task.wait(0.1)
	
-- 	local Character=self.sysCharacter 
-- 	self.player.main_inst.Character=Character
--     Character.Parent = workspace 
--     task.wait(0.1)
	
-- 	CarModel.Parent=workspace

--     local seat= self.Car:GetBody():GetSeatList()
--     for _,s in pairs(seat)  do
--         if  s:GetAttribute("isUsing") then
--             s:SetAttribute("isUsing",false)
--             s.Disabled = true
            
--         end
--     end
--     self.CarHumanoid:Destroy()
--     self.CarHumanoid = nil
	
-- 	Character:WaitForChild("Humanoid"):ChangeState(Enum.HumanoidStateType.Jumping)
-- 	Character:WaitForChild("Humanoid").WalkSpeed=gWalkSpeed
-- 	task.wait(0.1)

-- 	self.sysCharacter=nil
--     self.Car:SetCanCollide(false)
-- end;



-- --离开车(未使用)
-- function M.LeaveCar(self)
    
--     self.VectorForce.Enabled = false
--     self.AlignOrientation.Enabled = false

    

--     if  self.DriveConnection then
--         self.DriveConnection:Disconnect()
--         self.DriveConnection =nil
--     end
    
-- end;